package com.xc.freeapp.account.controller;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.xc.freeapp.exception.BaseException;
import com.xc.freeapp.exception.ExceptionMsg;
import com.xc.freeapp.util.Constant;
import com.xc.freeapp.util.TokenAnnotation;

public abstract class AbstractController {
	protected Logger log = Logger.getLogger(this.getClass());

	public HttpServletRequest getRequest() {
		HttpServletRequest curRequest = ((ServletRequestAttributes) RequestContextHolder
				.getRequestAttributes()).getRequest();
		return curRequest;
	}

	/**
	 * 参数验证出错异常捕获
	 * 
	 * @param ex
	 * @return
	 */
	@TokenAnnotation(required = false)
	@ExceptionHandler(MethodArgumentNotValidException.class)
	@ResponseStatus(value = HttpStatus.BAD_REQUEST)
	@ResponseBody
	public ExceptionMsg handleMethodArgumentNotValidException(
			MethodArgumentNotValidException ex) {
		BindingResult bindingResult = ex.getBindingResult();
		String errorMesssage = "参数错误:";

		for (FieldError fieldError : bindingResult.getFieldErrors()) {
			errorMesssage += fieldError.getDefaultMessage() + ";";
		}
		return new ExceptionMsg(Constant.VER_NOTNULL, errorMesssage);
	}

	@TokenAnnotation(required = false)
	@ExceptionHandler(BaseException.class)
	@ResponseStatus(value = HttpStatus.CREATED)
	@ResponseBody
	public ExceptionMsg handleBaseException(BaseException ex) {
		return new ExceptionMsg(ex.getCode(), ex.getMessage());
	}

	@TokenAnnotation(required = false)
	@ExceptionHandler(Exception.class)
	@ResponseStatus(value = HttpStatus.CREATED)
	@ResponseBody
	public ExceptionMsg handleException(Exception ex) {
		ex.printStackTrace();
		return new ExceptionMsg(Constant.GLOBAL_ERROR, ex.getMessage());
	}

}
